import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, NgForm, NgModel, Validators } from '@angular/forms';

import { MatCheckboxChange } from '@angular/material/checkbox';
import * as moment from 'moment';

import { InputOption } from '../../extensions/elements/inputs/shared/input-option.model';
import { CheckboxOption } from '../../extensions/elements/checkboxs/shared/checkbox-option.model';
import { SelectItem } from '../../extensions/elements/selects/shared/select-item.model';
import { SelectOption } from '../../extensions/elements/selects/shared/select-option.model';
import { DatePickerOption } from '../../extensions/elements/date-pickers/shared/date-picker-option.model';
import { RadioOption } from '../../extensions/elements/radios/shared/radio-option.model';
import { RegularExpressionConfig } from '../../core/config/regular-expression.config';
import { MaterialColorConfig } from '../../extensions/configs/colors/material-color/material-color.config';
import { ValidatorFactoryService } from '../../core/services/validator-factory.service';

@Component({
    selector: 'op-user-search-bar',
    templateUrl: './user-search-bar.component.html'
})
export class UserSearchBarComponent implements OnInit {
    @Output() searchData: EventEmitter<any> = new EventEmitter();
    formGroup: FormGroup;
    emailData: InputOption;
    nameData: InputOption;
    passwordData: InputOption;
    confirmPasswordData: InputOption;
    ageData: InputOption;
    statusData: SelectOption;
    startDateData: DatePickerOption;
    endDateData: DatePickerOption;
    marriedData: CheckboxOption;
    favoriteSeasonData: RadioOption;
    minDate: Date;
    maxDate: Date;
    legitimateNameOfRegExp = RegularExpressionConfig.legitimateName;

    constructor(
        private formBuilder: FormBuilder,
        private validatorFactory: ValidatorFactoryService,
    ) { }

    ngOnInit(): void {
        this.createForm();
        this.loadData();
    }

    onSearch(): void {
        if (this.formGroup.controls.startDate.value && (this.formGroup.controls.startDate.value) instanceof moment) {
            // this.formGroup.controls.startDate.setValue(this.formGroup.controls.startDate.value.format('YYYY/MM/DD'));
        }

        if (this.formGroup.controls.endDate.value && (this.formGroup.controls.endDate.value) instanceof moment) {
            // this.formGroup.controls.endDate.setValue(this.formGroup.controls.endDate.value.format('YYYY/MM/DD'));
        }

        this.searchData.emit(this.formGroup.value);
    }

    refresh(): void {
        this.createForm();
        this.searchData.emit(this.formGroup.value);
    }

    private createForm(): void {
        this.formGroup = this.formBuilder.group({
            email: '',
            name: ['', [
                Validators.required,
                Validators.minLength(2),
                Validators.maxLength(5),
                Validators.pattern(new RegExp(this.legitimateNameOfRegExp)),
            ]],
            password: ['', [
                Validators.required,
                Validators.minLength(5),
                Validators.maxLength(20)
            ]],
            confirmPassword: [''],
            age: ['', [
                Validators.min(18),
                Validators.max(80),
            ]],
            status: ['', [
                Validators.required
            ]],
            startDate: [''],
            endDate: [''],
            married: ['', [
                Validators.required
            ]],
            favoriteSeason: ['winter']
        });

        this.minDate = this.formGroup.controls.startDate.value ? this.formGroup.controls.startDate.value : null;
        this.maxDate = this.formGroup.controls.endDate.value ? this.formGroup.controls.endDate.value : null;

        /**
         * 当限制最大长度Validators.maxLength(number)和自带的Validators.email的验证同时存在是，需要动态去设置这两个验证
         */
        this.formGroup.get('email').setValidators([
            Validators.email,
            Validators.maxLength(30)
        ]);

        this.formGroup.get('confirmPassword').setValidators([
            Validators.required,
            Validators.minLength(6),
            Validators.maxLength(12),
            this.validatorFactory.getValueNotMatchValidatorDeprecated(this.formGroup.controls.password, this.formGroup.controls.confirmPassword)
        ]);

        this.formGroup.controls.password.valueChanges.subscribe(() =>
            this.validatorFactory.setValueNotMatchFieldModelError(this.formGroup.controls.password, this.formGroup.controls.confirmPassword)
        );

        this.formGroup.controls.startDate.valueChanges.subscribe(() => {
            let newValue = this.formGroup.controls.startDate.value;

            if (newValue instanceof moment) {
                // this.minDate = new Date(newValue.format('YYYY/MM/DD'));
            }
        });

        this.formGroup.controls.endDate.valueChanges.subscribe(() => {
            let newValue = this.formGroup.controls.endDate.value;

            if (newValue instanceof moment) {
                // this.maxDate = new Date(newValue.format('YYYY/MM/DD'));
            }
        });
    }

    getFavoriateApps(apps: string[]): void {
        this.formGroup.controls.favoriateApps.setValue(apps);
    }

    private loadData(): void {
        this.emailData = {
            labelTitle: '邮箱',
            placeholder: '例如：xxx@xxx.com',
            reactiveFormControl: this.formGroup.controls.email,
            type: 'email',
            maxLength: 30
        }

        this.nameData = {
            isRequired: true,
            labelTitle: '姓名',
            placeholder: '例如：张三',
            reactiveFormControl: this.formGroup.controls.name,
            maxLength: 5
        }

        this.passwordData = {
            isRequired: true,
            labelTitle: '密码',
            placeholder: '提示：密码长度5~20位',
            reactiveFormControl: this.formGroup.controls.password,
            type: 'password',
            maxLength: 20
        }

        this.confirmPasswordData = {
            isRequired: true,
            labelTitle: '确认密码',
            placeholder: '提示：请保持两次密码输入一致',
            reactiveFormControl: this.formGroup.controls.confirmPassword,
            type: 'password',
            maxLength: 20
        }

        this.ageData = {
            labelTitle: '年龄',
            placeholder: '提示：请输入18~80之间的数值',
            reactiveFormControl: this.formGroup.controls.age,
            type: 'number'
        }

        this.statusData = {
            isRequired: true,
            labelTitle: '段位',
            reactiveFormControl: this.formGroup.controls.status,
            allItems: [
                { name: '— —', value: 'all' },
                { name: '青铜', value: ' bronze' },
                { name: '白银', value: 'silver' },
                { name: '黄金', value: 'gold' },
                { name: '铂金', value: 'platnum' },
                { name: '钻石', value: 'diamond' },
                { name: '大师', value: 'master' },
                { name: '王者', value: 'challenger' }
            ]
        }

        this.startDateData = {
            labelTitle: '起始日期',
            reactiveFormControl: this.formGroup.controls.startDate,
            isTouchUI: true
        }

        this.endDateData = {
            labelTitle: '结束日期',
            reactiveFormControl: this.formGroup.controls.endDate,
            isTouchUI: true
        }

        this.marriedData = {
            labelTitle: '婚姻状况',
            name: '已婚',
            reactiveFormControl: this.formGroup.controls.married,
        }

        this.favoriteSeasonData = {
            labelTitle: '喜欢的季节',
            allItems: [
                { name: '春', value: 'spring' },
                { name: '夏', value: 'summer' },
                { name: '秋', value: 'autumn' },
                { name: '冬', value: 'winter' }
            ],
            reactiveFormControl: this.formGroup.controls.favoriteSeason
        }
    }
}